<template>
  <!-- 列表 -->
  <ContentWrap>
    <el-button
      type="primary"
      plain
      @click="openForm('create')"
      v-hasPermi="['exam:bank:create']"
    >
      <Icon icon="ep:plus" class="mr-5px"/>
      新增
    </el-button>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      row-key="id"
      :default-expand-all="isExpandAll"
      v-if="refreshTable"
    >
      <el-table-column label="id" align="center" prop="id" v-if="false"/>
      <el-table-column label="题库" align="center" prop="bankName"/>
      <el-table-column label="名称" align="center" prop="name"/>
      <el-table-column label="父章节" align="center" prop="parentId" v-if="false"/>
      <el-table-column label="显示顺序" align="center" prop="sort"/>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
  <!-- 表单弹窗：添加/修改 -->
  <BankChapterForm ref="formRef" @success="getList"/>
</template>
<script setup lang="ts">
import {DICT_TYPE} from '@/utils/dict'
import {dateFormatter} from '@/utils/formatTime'
import {BankApi} from '@/api/exam/bank'
import BankChapterForm from './BankChapterForm.vue'
import {BankChapterApi} from "@/api/exam/bankchapter";
import {handleTree} from "@/utils/tree";

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const props = defineProps<{
  bankId?: number // 题库id（主表的关联字段）
  bankName?: String // 题库名称
}>()
const loading = ref(false) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  bankId: undefined as unknown
})

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.bankId,
  (val: number) => {
    if (!val) {
      return
    }
    queryParams.bankId = val
    handleQuery()
  },
  {immediate: true, deep: true}
)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await BankChapterApi.getBankChapterList(queryParams)
    list.value = handleTree(data, 'id', 'parentId')
    list.value.forEach(item => {
      item.bankName = props.bankName;
    })
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  if (!props.bankId) {
    message.error('请选择一个题库')
    return
  }
  formRef.value.open(type, props.bankId, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BankApi.deleteBankChapter(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}

/** 展开/折叠操作 */
const isExpandAll = ref(true) // 是否展开，默认全部展开
const refreshTable = ref(true) // 重新渲染表格状态
const toggleExpandAll = async () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  await nextTick()
  refreshTable.value = true
}
</script>
